//
//  LZTComposeViewController.swift
//  LZTWeibo
//
//  Created by Yin jianxun on 16/8/17.
//  Copyright © 2016年 YinJianxun. All rights reserved.
//

import UIKit
import SVProgressHUD

class LZTComposeViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        
        setupUI()
    }
    
    //按钮的监听事件
    @objc func cancelAction() {
        
        //取消键盘第一响应
        composeTextView.resignFirstResponder()
        
        //取消时 dismiss当前VC
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    @objc func sendAction() {
        //发布
        
        //定义一个字符串 保存内容
        var allText: String = ""
        
        //遍历富文本 拿到 文字附件
        composeTextView.attributedText.enumerateAttributesInRange( NSRange(location: 0,length: composeTextView.attributedText.length) , options: []) { (result, range, _) in
            
            if let attachment = result["NSAttachment"] as? LZTTextAttachment {
                
                //代表 是文字附件（自己定义的类型）
                allText += attachment.emoticonModel?.chs ?? ""
                
                
            }else {
                
                //代表 发表的是普通字符串
                //此处之所以要转成OC的字符串，就是因为外层的遍历结果是OC的字符串
                let str = (self.composeTextView.attributedText.string as NSString).substringWithRange(range)
                allText += str
                
            }
        }
        
        //发布微博
        composePictureView.imageList.count == 0 ? update(allText) : upload(allText)
    }
    
    //设置试图
    func setupUI() {
        
        view.backgroundColor = UIColor.whiteColor()
        setupNavi()
        
        //添加控件
        view.addSubview(composeTextView)
        view.addSubview(composeBottomView)
        composeTextView.addSubview(composePictureView)
        //添加约束
        composeTextView.snp_makeConstraints { (make) in
            make.edges.equalTo(view).offset(UIEdgeInsetsZero)
        }
        composeBottomView.snp_makeConstraints { (make) in
            make.leading.bottom.trailing.equalTo(view)
            make.height.equalTo(44)
        }
        composePictureView.snp_makeConstraints { (make) in
            make.top.equalTo(composeTextView).offset(100)
            make.size.equalTo(CGSize(width: SCREENW - 20, height: SCREENW - 20))
            make.centerX.equalTo(composeTextView)
        }
        
        //监听底部View中按钮的点击回调
        //closure-02
        composeBottomView.closure = { [weak self] (type: LZTComposeBottomViewType) -> Void in
            
            //closure-04
            switch type {
            case .Picture:
                //选择图片
                self?.selectImage()
            case .Mention:
                print("picture")
            case .Trend:
                print("picture")
            case .Emoticon:
                //表情键盘 或者 系统键盘
                self?.switchKeyboard()
            case .Add:
                print("picture")
            }
        }
        
        //点击 加号图片跳转 相册
        composePictureView.closure = { [weak self] in
            
            self?.selectImage()
        }
        
        //注册通知  该通知监听键盘的frame将要改变
        NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(LZTComposeViewController.keyboardWillChangeFrame(_:)), name: UIKeyboardWillChangeFrameNotification, object: nil)
        
        //注册通知  该通知监听 表情键盘中删除按钮的点击事件
        NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(LZTComposeViewController.emoticonDeleteBtnNoti), name: WBEMOTICONDELETEBTNNOTIFICATION, object: nil)
        
        //注册通知  该通知监听 表情键盘中点击表情的点击事件
        NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(LZTComposeViewController.emoticonBtnNoti(_:)), name: WBEMOTICONBTNNOTIFICATION, object: nil)
    }
    
    //表情键盘中点击表情的点击事件
    func emoticonBtnNoti(noti: NSNotification) {
        
        guard let emoticonModel = noti.object as? LZTEmoticonModel else {
            return
        }
        
        //判断 emoji还是图片 表情
        if emoticonModel.isEmoji {
            
            //emoji表情
            //16进制的code转换
            let str = (emoticonModel.code ?? "" as NSString).emoji()
            //插入一个文本
            composeTextView.insertText(str)
            
            
        }else {
            //图片表情  借助富文本进行设置image
            
            //获取当前的富文本
            let allAttr = NSMutableAttributedString(attributedString: composeTextView.attributedText)
            
//            //创建一个 文字附件
//            let att = LZTTextAttachment()
//            
//            //属性赋值
//            att.emoticonModel = emoticonModel
//            
//            //设置文字附件的image
//            att.image = UIImage.emoticonImage(emoticonModel)
//            
//            //设置文字附件的bounds
//            //先计算行高
//            let lineHeight = UIFont.systemFontOfSize(16).lineHeight
//            
//            //图片和文字同时存在的时候，会发生变形，微调-4
//            att.bounds = CGRect(x: 0, y: -4, width: lineHeight, height: lineHeight)
//            
//            //创建一个 不可变的富文本
//            let attr = NSAttributedString(attachment: att)
            
            //
            let attr = NSAttributedString.emoticonAttributedString(emoticonModel, textFont: 16, y: -4)
            
            //获取 光标所选取的范围
            let selectRange = composeTextView.selectedRange
            
            //替换方式
            allAttr.replaceCharactersInRange(selectRange, withAttributedString: attr)
            
            //为了避免替换后 新加入的元素大小变化,可能是逐渐变小 需要设置font
            allAttr.addAttributes([NSFontAttributeName: UIFont.systemFontOfSize(16)], range: NSRange(location: 0, length: allAttr.length))
            
            //插入方式 -- 选中的部分不能被覆盖
            //allAttr.insertAttributedString(attr, atIndex: selectRange.location)
            
            //拼接 当前的富文本  -- 不能将 光标选中的目标进行替换
            //allAttr.appendAttributedString(attr)
            
            //将富文本添加到textView
            composeTextView.attributedText = allAttr
            
            //更改光标
            composeTextView.selectedRange = NSRange(location: selectRange.location + 1, length: 0)
            
            //发送一个系统通知：隐藏占位文字
            NSNotificationCenter.defaultCenter().postNotificationName(UITextViewTextDidChangeNotification, object: nil)
            
            //使用代理执行 协议方法
            composeTextView.delegate?.textViewDidChange!(composeTextView)
            
        }
        
    }
    
    //表情键盘中删除按钮的点击事件
    func emoticonDeleteBtnNoti() {
        
        //删除textView中textView的内容  从后往前删除，一个一个的删除
        composeTextView.deleteBackward()
        
    }
    
    
    func keyboardWillChangeFrame(noti: NSNotification) {
        
        //获取 键盘弹入弹出的动画时长
        guard let duration = noti.userInfo?["UIKeyboardAnimationDurationUserInfoKey"] as? Double else {
            return
        }
        
        //NSRange 是mac的类型 需要用NSValu进行CGRect转换
        guard let rect = noti.userInfo?["UIKeyboardFrameEndUserInfoKey"] as? NSValue else{
            return
        }
        let newRect = rect.CGRectValue()
                
        //更新 bottomView的约束
        composeBottomView.snp_updateConstraints { (make) in
            make.bottom.equalTo(view).offset(newRect.origin.y - SCREENH)
        }
        
        //设置动画
        UIView.animateWithDuration(duration) {
            
            //强制刷新
            self.view.layoutIfNeeded()
        }
        
    }
    
    func setupNavi() {
        
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", style: UIBarButtonItemStyle.Plain, target: self, action: #selector(LZTComposeViewController.cancelAction))
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "发布", style: UIBarButtonItemStyle.Plain, target: self, action: #selector(LZTComposeViewController.sendAction))
        
        //设置 发布按钮，开始时不能点击
        navigationItem.rightBarButtonItem?.enabled = false
        
        navigationItem.titleView = titleView
        
        
    }
    //懒加载 
    private lazy var titleView: UILabel = {
        
        //显示用户的昵称
        let name = LZTUserAccountViewModel.sharedTools.userAccount!.screen_name!
        let str = "发微博\n\(name)"
        
        //截取富文本的range（范围）
        let range = (str as NSString).rangeOfString(name)
        
        //初始化一个富文本
        let attr = NSMutableAttributedString(string: str)
        
        //设置富文本
        attr.addAttributes([NSForegroundColorAttributeName: AppThemeColor,
            NSFontAttributeName: UIFont.systemFontOfSize(12)], range: range)
        
        let lab = UILabel()
        lab.numberOfLines = 0
        lab.attributedText = attr
        lab.textAlignment = .Center
        lab.sizeToFit()
        return lab
        
    }()
    
    //自定义textView的懒加载
    private lazy var composeTextView: LZTComposeTextView = {
       
        let view = LZTComposeTextView()
        view.delegate = self
        //设置占位文字的大小
        view.font = UIFont.systemFontOfSize(16)
        //设置占位文字内容
        view.placeHolder = "请输入发表内容"
        //允许上下移动
        view.alwaysBounceVertical = true
        
        return view
    }()
    
    //自定义底部试图
    private lazy var composeBottomView: LZTComposeBottomView = LZTComposeBottomView()
    
    //自定义的视图
    private lazy var composePictureView: LZTComposePictureView = LZTComposePictureView()
    
    //自定义 表情键盘
    private lazy var emoticonKeyboardView: LZTEmoticonKeyboardView = LZTEmoticonKeyboardView(frame: CGRect(x: 0, y: 0, width: SCREENW, height: 216))
    
    //析构函数 销毁通知
    deinit{
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }
}

//发布按钮的可点击和不可点击
extension LZTComposeViewController: UITextViewDelegate{
    
    func textViewDidChange(textView: UITextView) {
        
        navigationItem.rightBarButtonItem?.enabled = textView.hasText()
        
    }
    
    func scrollViewDidScroll(scrollView: UIScrollView) {
        //取消键盘的第一响应
        self.composeTextView.resignFirstResponder()
    }
    
}


//发布按钮对应的extension
extension LZTComposeViewController {
    //发布文字微博
    func update(status: String) {
        
        LZTNetworkTools.sharedTools.composeUpdate(status, success: { (response) in
            SVProgressHUD.showSuccessWithStatus("发布成功")
            
            }) { (error) in
                SVProgressHUD.showErrorWithStatus("发送失败")
        }
    }
    
    //发布 图片微博
    func upload(status: String) {
        
        LZTNetworkTools.sharedTools.composeUpload(status, images: composePictureView.imageList, success: { (response) in
            
            SVProgressHUD.showSuccessWithStatus("发布成功")
            }) { (error) in
                SVProgressHUD.showErrorWithStatus("发送失败")
        }
    }
}

//处理 底部View按钮的点击事件
extension LZTComposeViewController {
    
    //选择图片
    func selectImage() {
        
        let pickerVc = UIImagePickerController()
        //设置代理 得到选中图片
        pickerVc.delegate = self
        self.presentViewController(pickerVc, animated: true, completion: nil)
        
    }
    
    //切换键盘
    func switchKeyboard() {
        
        //composeTextView.inputView中加上自定义表情键盘
        if composeTextView.inputView == nil {
            
            //代表：系统键盘
            composeTextView.inputView = emoticonKeyboardView
            //表情键盘的状态
            composeBottomView.isEmticon = true
            
        }else {
            //代表：自定义表情键盘
            composeTextView.inputView = nil
            //表情键盘的状态
            composeBottomView.isEmticon = false
        }
        //刷新
        composeTextView.reloadInputViews()
        //textView成为第一下响应者
        composeTextView.becomeFirstResponder()
    }
    
}

//处理 picker的代理方法
extension LZTComposeViewController: UIImagePickerControllerDelegate, UINavigationControllerDelegate {
    
    func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) {
        
        let image = info["UIImagePickerControllerOriginalImage"] as! UIImage
        
        //压缩图片
        //let imageScale = UIImage.dealImageScale(image, width: 600)
        
        //设置composeTextView的背景颜色 通过image的渲染
        //composeTextView.backgroundColor = UIColor(patternImage: image)
        
        //调动：压缩后的图片的加入
        composePictureView.addImages(UIImage.dealImageScale(image, width: 600))
        
        //关闭控制器
        picker.dismissViewControllerAnimated(true, completion: nil)
        
    }
    
    //代理方法实现时，原先自带的 取消 系统将不会再实现而是需要自己去实现
    func imagePickerControllerDidCancel(picker: UIImagePickerController) {
        //关闭VC
        picker.dismissViewControllerAnimated(true, completion: nil)
    }
}

